<template>
    <div>
      <button @click="getLocation">获取位置</button>
      <div v-if="location">
        <p>位置信息：{{ location.formattedAddress }}</p>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        location: null,
      };
    },
    methods: {
      getLocation() {
        if (!navigator.geolocation) {
          alert('您的浏览器不支持地理位置服务');
          return;
        }
  
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            this.getAddress(lat, lng);
          },
          (error) => {
            console.error('获取位置失败', error);
            alert('获取位置失败');
          },
          {
            enableHighAccuracy: true,
            timeout: 10000,
            maximumAge: 0,
          }
        );
      },
      getAddress(lat, lng) {
        // 使用高德地图API进行逆地理编码
        AMap.plugin('AMap.Geolocation', () => {
          const geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,
            timeout: 10000,
          });
          geolocation.getAddress([lng, lat], (status, result) => {
            if (status === 'complete' && result.info === 'SUCCESS') {
              this.location = result;
            } else {
              console.error('逆地理编码失败', result);
              alert('逆地理编码失败');
            }
          });
        });
      },
    },
  };
  </script>
  
  <style scoped>
  /* 你可以在这里添加一些样式 */
  </style>